<template>
  <div class="wh-full flex-col overflow-hidden bg-gray-100 dark:bg-gray-800" dark="text-white">
    <header border-b="1 solid #eee" class="sticky bg-primary text-white" dark="bg-dark border-0">
      <div class="m-auto f-c-c px-24" :style="`height: ${header.height}px`">
        <div class="flex cursor-pointer items-center" @click="$router.push('/')">
          <img src="@/assets/images/logo.png" height="44" class="mr-30" />
        </div>
        <div class="h-full flex flex-1 items-center gap-y-20px">
          <n-button v-if="catId" secondary round @click="$router.back()">
            <template #icon>
              <SvgIcon icon="return" color="white"></SvgIcon>
            </template>
            <span text-white>返回</span>
          </n-button>
          <div>截止时间为：{{ exam ? formatDateTime(exam.endtime) : '' }}，</div>
          <div v-if="leftTime > 0">剩余 {{ day }} 天 {{ hour }}:{{ minute }}:{{ second }}</div>
          <div v-else>已结束</div>
        </div>

        <div
          v-if="userStore.getRole().length > 0 && userStore.getRole().some((r) => r === 'student')"
        >
          <UserAvatar />
        </div>
      </div>
    </header>
    <section class="min-h-300 flex-col flex-1 items-center">
      <div class="h-full w-full p-16">
        <!-- 分屏 -->
        <n-split direction="horizontal" :min="0.3" :max="0.7" :resize-trigger-size="4">
          <template #1>
            <div class="mr-8 box-border h-full rounded-5 bg-white px-10 pt-10 dark:bg-dark">
              <n-tabs
                class="h-full"
                type="line"
                :value="activeTab"
                @update:value="handleUpdateValue"
              >
                <!-- 题目详情Tab -->
                <n-tab-pane
                  :name="PROBLEM_TAB_NAMES.DETAIL"
                  tab="题目详情"
                  class="h-full overflow-auto"
                  display-directive="show"
                >
                  <ProblemDetail />
                </n-tab-pane>
                <!-- more tabs -->
                <slot name="tab1"></slot>
                <slot name="tab2"></slot>
                <slot name="tab3"></slot>
                <slot name="tab4"></slot>
              </n-tabs>
            </div>
          </template>
          <template #2>
            <div class="relative ml-8 h-full">
              <ProblemSolution />
            </div>
          </template>
        </n-split>
      </div>
    </section>
  </div>
</template>

<script setup>
import { header } from '~/settings'
import { useUserStore } from '@/store'
import api from '@/api/user'
import ProblemDetail from '@/components/problem-tabs/ProblemDetail.vue'
import ProblemSolution from '@/components/problem-tabs/ProblemSolution.vue'
import { PROBLEM_TAB_NAMES } from '@/constant'
import UserAvatar from '@/layout/components/header/components/UserAvatar.vue'
import { useCountdown } from '@/composables'
import { formatDateTime, encryptASE } from '@/utils'

const userStore = useUserStore()
const { leftTime, startCountdown, clearCountdown, day, hour, minute, second } = useCountdown()

const route = useRoute()
const { catId, continueTrain } = route.query
const { examId, problemId } = useRoute().params
const activeTab = ref(PROBLEM_TAB_NAMES.DETAIL) //当前标签
const exam = ref(null) // 本次考试
const problem = ref(null) //当前题目
const category = ref(null) // 题目分类
const canSubmitProblem = ref(false) // 是否可提交题目
const sourceCode = ref('') // 当前编辑的代码
const language = ref(null) // 选择的代码编程语言
const compiler = ref(null) // 选择的代码编译器
const lastSubmittedCode = ref('') // 最后一次提交的代码
const lastSubmittedCodeTime = ref(0) // 最后一次提交时间(时间戳)
const lastSubmittedResult = ref(null) // 最后一次提交的结果

const handleUpdateValue = (val) => {
  activeTab.value = val
}

/********  封装接口，用于注入到子孙组件  *********/
// 提交代码
const submitCodeByIdApi = async (lang, code, comp) => {
  const encryptedCode = encryptASE(code)
  if (catId) {
    await api.itrainSubmitCodeById({
      examId,
      problemId,
      catId,
      language: lang,
      sourceCode: encryptedCode,
      compiler: comp,
    })
  } else {
    await api.submitCodeById({
      examId,
      problemId,
      language: lang,
      sourceCode: encryptedCode,
      compiler: comp,
    })
  }

  // 提交代码成功
  lastSubmittedCode.value = sourceCode.value
  lastSubmittedCodeTime.value = Date.now()
  activeTab.value = PROBLEM_TAB_NAMES.RESULT
}
// 获取运行结果
const getAllWrongAndRightCasesApi = async () => {
  if (catId) {
    return await api.getItrainAllWrongAndRightCases({
      examId,
      problemId,
      catId,
    })
  }
  return await api.getAllWrongAndRightCases({
    examId,
    problemId,
  })
}

// 查看运行结果的某个用例
const getCaseHintApi = async (problemtestcasesId, wrongcasesId) => {
  if (catId) {
    return api.getCaseItrainHint({
      examId,
      problemId,
      catId,
      problemtestcasesId, //问题的用例
      wrongcasesId, //学生提交后产生的错误测试用例
    })
  }
  return api.getCaseHint({
    examId,
    problemId,
    problemtestcasesId, //问题的用例
    wrongcasesId, //学生提交后产生的错误测试用例
  })
}

/********  页面初始化请求  *********/
// 获取当前考试信息
const getExamInfo = async () => {
  try {
    const res = await api.getExamInfo({
      examId,
    })
    exam.value = res.data
  } catch (err) {
    console.log(err)
  }
}

const getCategoryInfo = async () => {
  if (!catId) return
  try {
    const res = await api.getCategoryInfo({
      examId,
      catId,
    })
    category.value = res.data
  } catch (error) {
    console.log(error)
  }
}

// 获取本题是否能提交
const getIsSubmitThisProblem = async () => {
  try {
    const res = await api.isSubmitThisProblem({
      examId,
      problemId,
      catId,
    })
    //可以提交
    canSubmitProblem.value = !res.data.problemIsSubmit
  } catch (err) {
    //出错代表不能提交本题（已经提交过了，或者服务器/网络错误）
    canSubmitProblem.value = false
  }
}

// 获取最近一次提交
const getLastSolution = async () => {
  try {
    const res = await api.getLastSolution({
      examId,
      problemId,
    })

    sourceCode.value = res.data ? res.data.sourceCode : ''
  } catch (err) {
    console.log(err)
  }
}

getExamInfo()
getCategoryInfo()
getIsSubmitThisProblem()
getLastSolution()

/******** provide 变量 *******/
provide('problem/idsValue', {
  examId,
  problemId,
  catId,
  continueTrain,
})
provide('problem/exam', readonly(exam))
provide('problem/category', readonly(category))
provide('problem/problem', problem)
provide('problem/activeTab', activeTab)
provide('problem/canSubmitProblem', canSubmitProblem)
provide('problem/sourceCode', sourceCode)
provide('problem/language', language)
provide('problem/compiler', compiler)
provide('problem/lastSubmittedCode', lastSubmittedCode)
provide('problem/lastSubmittedCodeTime', lastSubmittedCodeTime)
provide('problem/lastSubmittedResult', lastSubmittedResult)

provide('problem/submitCodeByIdApi', submitCodeByIdApi)
provide('problem/getAllWrongAndRightCasesApi', getAllWrongAndRightCasesApi)
provide('problem/getCaseHintApi', getCaseHintApi)

/******** 生命周期 *******/
onMounted(async () => {
  try {
    const res = await api.getSyncTime({
      params: { examId },
    })
    startCountdown(Math.floor(res.data.leftTime / 1000)) // 舍弃毫秒, 开始倒计时
  } catch (err) {
    console.log(err)
  }
})

onBeforeUnmount(() => {
  clearCountdown()
})
</script>
